package com.cl.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.cl.safe.R;
import com.cl.service.GPSService;

public class SMSReceiver extends BroadcastReceiver {

	private static final String TAG = "SMSReceiver";

	@Override
	public void onReceive(Context context, Intent intent) {
		Object[] objs = (Object[]) intent.getExtras().get("pdus");
		//一个obj对应一条短信
		for(Object obj : objs) {
			SmsMessage sms = SmsMessage.createFromPdu((byte[]) obj);
			String body = sms.getMessageBody();
			String phone = sms.getOriginatingAddress();
			if(phone.contains("4342")) {
				if("#*location*#".equals(body)){
					//获得手机位置地址
					Log.e(TAG, "获得手机位置地址");
					Intent service = new Intent(context, GPSService.class);
					context.startService(service);
					SharedPreferences sp = context.getSharedPreferences("config", context.MODE_PRIVATE);
					String lastLocation = sp.getString("lastLocation", "");
					if(TextUtils.isEmpty(lastLocation)) {
						Toast.makeText(context, "请稍等，正在获取位置", 1).show();
					}else {
						SmsManager.getDefault().sendTextMessage(phone, null, lastLocation, null, null);
					}
					abortBroadcast();
				}else if("#*alarm*#".equals(body)){
					//手机报警
					Log.e(TAG, "手机报警");
					abortBroadcast();
					MediaPlayer player = MediaPlayer.create(context, R.raw.ylzs);
					player.setVolume(1.0f, 1.0f);
					player.setLooping(false);
					player.start();
					
				}else if("#*lockscreen*#".equals(body)){
					//远程锁屏
					Log.e(TAG, "远程锁屏");
					abortBroadcast();
				}else if("#*wipedata*#".equals(body)){
					//清除手机数据
					Log.e(TAG, "清楚数据");
					abortBroadcast();
				}
			}
		}
		
	}
	
}